package com.accompany.fragment.home;

import static android.content.Context.MODE_PRIVATE;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.accompany.R;
import com.accompany.adapter.BaseRecyclerHolder;
import com.accompany.adapter.BaseRecyclerRefreshAdapter;
import com.accompany.api.bean.GrabOrdersMesgBean;
import com.accompany.api.bean.MenuItemBean;
import com.accompany.api.bean.TakeOrderDetialsBean;
import com.accompany.api.category.GrabOrdersCategory;
import com.accompany.api.presenter.GrabOrderPresenter;
import com.accompany.base.BaseBean;
import com.accompany.base.BaseFragment;
import com.accompany.dialog.LoginOutDialog;
import com.accompany.dialog.RoundCornerDialog;
import com.accompany.fragment.home.activity.TakeOrdersDetialsActivity;
import com.accompany.fragment.login.UserLoginActivity;
import com.accompany.listener.OnQuiteDialogClickListener;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.main.MainActivity;
import com.accompany.utils.HttpNetworkConnectUtils;
import com.accompany.utils.LocationUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ServicePhoneUtils;
import com.accompany.utils.ToastUtil;
import com.accompany.view.DropPopMenu;
import com.accompany.view.RecyclerViewLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 信息说明: 首页界面
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/14 15 ：49
 * 项目名称：yuanban
 */
@SuppressWarnings({"all"})
public class HomeFragment extends BaseFragment implements GrabOrdersCategory.View, OnRefreshListener, OnLoadMoreListener {
    @BindView(R.id.base_refresh_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.lineart_top)
    LinearLayout mLinearLayout;
    @BindView(R.id.text_top)
    TextView mTopMsg;
    @BindView(R.id.iocn_top)
    ImageView mIconImageTop;
    @BindView(R.id.relet_home)
    RelativeLayout mRelatHome;
    @BindView(R.id.relat_empty_bottom)
    RelativeLayout mRelatEmpty;
    @BindView(R.id.iocn_emtpty)
    ImageView iocnEmtpty;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.back_left)
    ImageView backLeft;

    @BindView(R.id.call)
    TextView call;
    @BindView(R.id.relat_cert_bottom)
    RelativeLayout relatCertBottom;
    @BindView(R.id.relat_hand_offline)
    RelativeLayout relatHandOffline;

    private GrabOrderPresenter mPresenter;
    private List<GrabOrdersMesgBean.OrderMsgBeanData.OrderMsgBeanDataList> mlist = new ArrayList<>();
    private String mToken;
    private BaseRecyclerRefreshAdapter<GrabOrdersMesgBean.OrderMsgBeanData.OrderMsgBeanDataList> mAdapter;
    private int pageNumber = 1;
    private boolean isLoading;
    @BindView(R.id.relat_empty)
    RelativeLayout mEmptyLayout;
    @BindView(R.id.base_refresh)
    SmartRefreshLayout smartRefreshLayout;
    private long mOrderId;
    private String Address;
    private LoginOutDialog dialog;
    private GrabOrdersMesgBean grabOrdersMesgBean;
    private boolean isHandOff,isLogin = false;
    private long  mUserId;
    private String isAuth = "0";
    private Context activity;
    AlertDialog alertDialog =null;
//    private Timer time;
//    private TimerTask timerTask;
    /**
     * 定位
     */
    private void initLocation() {
        Location location = LocationUtils.getInstance(getActivity()).showLocation();
        if (location != null) {  //
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
            mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);

            isLogin = sharedPreferences.getBoolean("isLogin",false);
            Address = location.getLatitude() + "," + location.getLongitude();
            JSONObject result = new JSONObject();
            try {
                result.put("acdId", mUserId);
                result.put("isService", "0");
                result.put("cityId", "620100");
                result.put("location", Address);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
            if (!HttpNetworkConnectUtils.isNetworkConnected(getActivity())) {
                ToastUtil.showToastERROR(getActivity(), "网络不给力,请稍后重试");
            } else if(isLogin){//登录的时候请求接口
                mPresenter.getLocation(mToken, result.toString());
                mPresenter.getGrabOrderList(pageNumber, mToken, 2);
            }else {//没登录不请求接口,  显示无数据

                mEmptyLayout.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
            }
        }
        else {
            //提示手动打开dps
//            ToastUtil.showToastWARNING(getActivity(),"请打开dps定位功能");
            openGPS();
        }
    }
    @Override
    public int getLayoutResource() {
        return R.layout.fragment_home_view;
    }
    @Override
    public void onResume() {
        super.onResume();
        activity = getActivity();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        isLogin = sharedPreferences.getBoolean("isLogin",false);
        if (isLogin) {
            initLocation();
            smartRefreshLayout.autoRefresh();
        }else {
            setOffline("0");
        }
    }

    @Override
    public void initLayoutView() {


        mPresenter = new GrabOrderPresenter(this);
        SetPersenter(mPresenter);
        activity = getActivity();
        mLinearLayout.getBackground().setAlpha(30);
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        } else {
            initLocation();//初始化定位信息
        }
        getPhonePermission();
        RecyclerViewLayoutManager.setLinearVerticalManager(getActivity(), mRecyclerView);
        mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
        mAdapter = new BaseRecyclerRefreshAdapter<GrabOrdersMesgBean.OrderMsgBeanData.OrderMsgBeanDataList>(getActivity(), mlist, R.layout.home_item_view) {
            @Override
            public void convert(BaseRecyclerHolder holder, GrabOrdersMesgBean.OrderMsgBeanData.OrderMsgBeanDataList item, int position, boolean isScrolling) throws IOException {
                holder.setText(R.id.order_name, item.getTitle());
                holder.setText(R.id.order_price, String.valueOf(item.getPrice()));
                holder.setText(R.id.name, item.getOrderDTO().getPatientName());
                TextView mGender = holder.getView(R.id.gender_home);
                if (item.getOrderDTO().getPatientSex() != null) {
                    if (item.getOrderDTO().getPatientSex().equals("0")) {
                        mGender.setText("女");
                    } else if (item.getOrderDTO().getPatientSex().equals("1")) {
                        mGender.setText("男");
                    }
                }
                holder.setText(R.id.age_home, item.getOrderDTO().getPatientAge());
                holder.setText(R.id.order_yiyuan, item.getOrderDTO().getHospitalName());
                holder.setText(R.id.order_shiduan, item.getOrderDTO().getPeriodStr());
                holder.getView(R.id.take_orders).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RoundCornerDialog mDialodialogg = new RoundCornerDialog(getActivity(), "是否要确定要抢单？", "确定", "取消", new OnQuiteDialogClickListener() {
                            @Override
                            public void onConfirm(Dialog dialog) {
                                mOrderId = mlist.get(position).getId();
                                JSONObject result = new JSONObject();
                                try {
                                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
                                    long mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
                                    result.put("acdId", mUserId);
                                    result.put("id", mlist.get(position).getId());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                mPresenter.getTakeOrderDetial(mToken, result.toString());
                                mAdapter.notifyDataSetChanged();
                                smartRefreshLayout.autoRefresh();
                                dialog.dismiss();
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();
                            }
                        });
                        mDialodialogg.show();
                    }
                });
            }
        };
        mAdapter.setDatas(mlist);
        mRecyclerView.setAdapter(mAdapter);
        mPresenter.getGrabOrderList(pageNumber, mToken, 2);
        smartRefreshLayout.setOnLoadMoreListener(this);
        smartRefreshLayout.setOnRefreshListener(this);
        getAuthStatus();
        // TODO: 2022/6/16 开始定时刷新
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable,5000);
//        time=new Timer();
//        timerTask=new TimerTask() {
//            @Override
//            public void run() {
//                mPresenter.getGrabOrderList(pageNumber, mToken, 2);
//            }
//        };
//        time.scheduleAtFixedRate(timerTask,5000,5000); //延时1000ms后开始，每100ms一次

    }
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run () {
            // TODO: 2022/6/16 间隔5秒刷新一次数据
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
            if (sharedPreferences != null && (isLogin = sharedPreferences.getBoolean("isLogin",false))){
                mPresenter.getGrabOrderList(pageNumber, mToken, 2);
                handler.postDelayed(this,5000);
            }

        }
    };
    /**
     * 获取打电话权限
     */
    private void getPhonePermission() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 若没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.CALL_PHONE)) {
                // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                //  如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                // 弹窗需要解释为何需要该权限，再次请求授权
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent call = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                call.setData(uri);
                startActivity(call);
            } else {
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.CALL_PHONE},
                        0);
            }
        }
    }

    // 获取认证状态   未认证切换为离线状态  1认证  0未认证
    private void getAuthStatus() {
        isAuth = (String) SPUtils.get(getActivity(), "isIdentification", "0");
        if (isAuth.equals("0")) {//切换为离线,不可点击切换状态
            changeOffLine(false);
            mLinearLayout.setEnabled(false);
            mLinearLayout.setClickable(false);
        } else if (isAuth.equals("1")) {
            smartRefreshLayout.setVisibility(View.VISIBLE);
            mLinearLayout.setEnabled(true);//认证状态,  可以手动设置离线
            mLinearLayout.setClickable(true);

        }
    }

    //切换离线 在线
    @OnClick({R.id.lineart_top, R.id.call, R.id.hand_inline})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.lineart_top://  只能在认证情况下点击
                changStatus();
                break;
            case R.id.call:
                //弹窗打电话
                ServicePhoneUtils.call(getActivity());
                break;
            case R.id.hand_inline:
                ServicePhoneUtils.call(getActivity());
                break;
        }

    }

    //切换离线在线
    public void changStatus() {
        DropPopMenu dropPopMenu = new DropPopMenu(getActivity());
        dropPopMenu.setTriangleIndicatorViewColor(Color.WHITE);
        dropPopMenu.setBackgroundResource(R.drawable.bg_drop_pop_menu_white_shap);
        dropPopMenu.setItemTextColor(Color.BLACK);
        dropPopMenu.setIsShowIcon(true);
        dropPopMenu.setOnItemClickListener(new DropPopMenu.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id, MenuItemBean menuItem) {
                if (menuItem.getItemId() == 1) {  //认证转态下在线
                    mIconImageTop.setBackgroundResource(R.drawable.zaixian_duihao_bg);
                    mTopMsg.setText(menuItem.getItemTitle());
                    mRelatHome.setVisibility(View.VISIBLE);
                    mRelatEmpty.setVisibility(View.GONE);
                    String str = updataeStatus("0");
                    String mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
                    mPresenter.getLocation(mToken, str);
                    changeOffLine(true);
                } else if (menuItem.getItemId() == 2) {//认证转态下离线
                    mTopMsg.setText("离线");
                    String str = updataeStatus("1");
                    mPresenter.getLocation(mToken, str);
                    String mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
                    setOffline(isAuth);
                }
            }
        });
        dropPopMenu.setMenuList(getIconMenuList());
        dropPopMenu.show(mLinearLayout);
    }

    //配置离线  在线参数  修改陪诊员状态
    public  String  updataeStatus(String status){
        JSONObject result = new JSONObject();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        long mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        try {
            result.put("acdId", mUserId);
            result.put("isService", status);// 是否在线 0在线 1离线
            result.put("cityId", "620100");
            result.put("location", Address);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return String.valueOf(result);
    }

    //切换为离线
    public void changeOffLine(boolean flag) {
        if (flag) {//认证状态下
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
            long mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
            JSONObject result = new JSONObject();
            try {
                result.put("acdId", mUserId);
                result.put("isService", "0");
                result.put("cityId", "620100");
                result.put("location", Address);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
            mPresenter.getLocation(mToken, result.toString());
            mIconImageTop.setBackgroundResource(R.drawable.zaixian_duihao_bg);
            mRelatHome.setVisibility(View.VISIBLE);
            mRelatEmpty.setVisibility(View.GONE);
            relatCertBottom.setVisibility(View.GONE);
            relatHandOffline.setVisibility(View.GONE);
            smartRefreshLayout.setVisibility(View.VISIBLE);
            mTopMsg.setText("在线");
        } else {//未认证状态
            mTopMsg.setText("离线");
            mRelatHome.setVisibility(View.GONE);
            mRelatEmpty.setVisibility(View.GONE);
            relatCertBottom.setVisibility(View.VISIBLE);
            relatHandOffline.setVisibility(View.GONE);
            mIconImageTop.setBackgroundResource(R.drawable.lixian_red_bg);
            smartRefreshLayout.setVisibility(View.GONE);
        }
    }

    private List<MenuItemBean> getIconMenuList() {
        List<MenuItemBean> list = new ArrayList<>();
        list.add(new MenuItemBean(R.drawable.zaixian_duihao_bg, 1, "在线"));
        list.add(new MenuItemBean(R.drawable.lixian_red_bg, 2, "离线"));
        return list;
    }

    @Override
    public void getLocation(BaseBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
        } else {
            ToastUtil.showToastINFO(getActivity(), bean.getMsg());
        }
    }

    @Override
    public void getGrabOrderList(GrabOrdersMesgBean baseBean) {
        grabOrdersMesgBean = baseBean;

        if (baseBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {//请求成功
            if (baseBean.getData() != null && baseBean.getData().getList().size() > 0) {
                if (pageNumber == 1) {//第一次请求
                    if (isLoading) {//isLoading == true,上拉
                        isLoading = false;
                    } else {//刷新
                        mlist.clear();
                    }
                    mlist.addAll(baseBean.getData().getList());
                    mAdapter.setDatas(baseBean.getData().getList());
                    smartRefreshLayout.setEnableLoadMore(true);
                } else {// 上拉
                    if (baseBean.getData().isHasNextPage()) {
                        mlist.addAll(mlist.size(), baseBean.getData().getList());
                        mAdapter.add(baseBean.getData().getList());
                        smartRefreshLayout.setEnableLoadMore(true);
                    } else {
                        ToastUtil.showToastINFO(getActivity(), "没有更多数据");
                    }

                }
                mEmptyLayout.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
            } else {// 列表无数据
                if (isLoading) {
                    isLoading = false;
                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                }
            }
        } else if (!isLogin ) {//未登录  baseBean.getCode() == ConstantStaticUrl.NO_LOGIN_CODE
            if(dialog == null){
                dialog = LoginOutDialog.getLoginOutDialog(activity);
            }
            dialog.show();
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialog!=null && dialog.isShowing()){
                        dialog.dismiss();
                    }
                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(getActivity());
                    getActivity().finish();
                    dialog.dismiss();
                    dialog = null;
                }
            });

        } else {//服务器返回错误信息
            ToastUtil.showToastINFO(getActivity(), baseBean.getMsg());
        }
    }

    @Override
    public void getTakeOrderDetial(TakeOrderDetialsBean baseBean) {

        if (baseBean != null) {
            if (baseBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
                if (baseBean.getData() != null && baseBean.getData().getIflock() != null && baseBean.getData().getIflock().equals("0")) {
                    Bundle bundle = new Bundle();
                    bundle.putLong("orderId", mOrderId);
                    openActivityWitchAnimation(TakeOrdersDetialsActivity.class, bundle);
                } else if (baseBean.getData() != null && baseBean.getData().getIflock() != null && baseBean.getData().getIflock().equals("1")) {
                    ToastUtil.showToastINFO(getActivity(), "该订单已被别人抢走~~");
                }
            } else {
                ToastUtil.showToastINFO(getActivity(), baseBean.getMsg());
            }
        }

    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(getActivity(), mErrorMsg);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        mPresenter.getGrabOrderList(pageNumber, mToken, 2);
        smartRefreshLayout.finishRefresh(500);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (grabOrdersMesgBean.getData().isHasNextPage()) {
            isLoading = true;
            pageNumber++;
            smartRefreshLayout.setEnableLoadMore(true);
            mPresenter.getGrabOrderList(pageNumber, mToken, 2);

        } else {
            isLoading = false;
        }

        smartRefreshLayout.finishLoadMore(500);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200://刚才的识别码
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                    initLocation();//开始定位
                } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                    ToastUtil.showToastINFO(getActivity(), "未开启定位权限,请手动到设置去开启权限");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //停止计时
        handler.removeCallbacks(runnable);
//        timerTask.cancel();
    }

    public void setOffline(String isAuth){
        mTopMsg.setText("离线");
        mIconImageTop.setBackgroundResource(R.drawable.lixian_red_bg);
        smartRefreshLayout.setVisibility(View.GONE);
        mRelatHome.setVisibility(View.GONE);
        mRelatEmpty.setVisibility(View.GONE);
        if (isAuth.equals("1")){//认证离线
            relatHandOffline.setVisibility(View.VISIBLE);
            relatCertBottom.setVisibility(View.GONE);
        }else if(isAuth.equals("0")){//未认证离线
            relatCertBottom.setVisibility(View.VISIBLE);
            relatHandOffline.setVisibility(View.GONE);
        }
    }



    private void openGPS() {
        alertDialog = new AlertDialog.Builder(getActivity())
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle("现在去打卡GPS使用更多功能")
                .setMessage("开启定位")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,887);
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case 887:
                //开启GPS，从新添加地理监听
//                startLocation();
                alertDialog.dismiss();
                initLocation();
                break;
            default:break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (dialog != null &&  dialog.isShowing()){
            dialog.dismiss();
        }
    }
}
